package org.example.controller;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.example.annotation.Auth;
import org.example.enums.AuthEnum;
import org.example.utils.JwtUtils;
import org.example.result.Result;
import org.example.utils.OnlineUtil;
import org.example.webSocket.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @BelongsProject：blockchain-APTrace
 * @CreateTime 2024-05-25-10:30
 * @Author SweetPig
 */
@RestController
@RequestMapping("online")
public class OnlineController {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WebSocketServer webSocketServer;

    @RequestMapping("onlineList")
    public Result onlineList() {
        Map<String, Object> online = OnlineUtil.online(redisTemplate);
        return Result.success(online);
    }

    /**
     * 强制下线
     *
     * @return
     */
    @Auth(value = {AuthEnum.ADMIN})
    @RequestMapping("removeOnline/{id}")
    public Result removeOnline(@PathVariable("id") String id) {
        String token = JwtUtils.create(id);
        webSocketServer.onClose(token);
        //清除key
        redisTemplate.delete("online_user_" + id);
        webSocketServer.sendToAllClient(JSONUtil.toJsonStr(OnlineUtil.online(redisTemplate)));
        return Result.success();
    }

    /**
     * 退出用户
     *
     * @param token
     * @return
     */
    @RequestMapping("loginOut/{token}")
    public Result loginOut(@PathVariable("token") String token) {
        JSONObject entries = JwtUtils.of(token);
        webSocketServer.onClose(token);
        //清除key
        redisTemplate.delete("online_user_" + entries.get("id"));
        webSocketServer.sendToAllClient(JSONUtil.toJsonStr(OnlineUtil.online(redisTemplate)));
        return Result.success();
    }
}
